package com.yq.testmodule.hook;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: user
 * @date: 2023/3/17
 */
public class HookAMS {
    private static final String TARGET_INTENT = "target_intent";
    @SuppressLint("PrivateApi")
    public static void hookAMS(Context context) throws Exception {
        //获取singleton对象
        Field iActivityTaskManagerSingleton = Class.forName("android.app.ActivityTaskManager").getDeclaredField("IActivityTaskManagerSingleton");
        iActivityTaskManagerSingleton.setAccessible(true);
        Object singleton = iActivityTaskManagerSingleton.get(null);

        //获取SingleTon 的mInstance
        Class<?> singletonClass = Class.forName("android.util.Singleton");
        Field mInstanceField  = singletonClass.getDeclaredField("mInstance");
        mInstanceField .setAccessible(true);
        Object mInstance = mInstanceField.get(singleton);

        //设置动态代理对象
        Class<?> clas = Class.forName("android.app.IActivityTaskManager");
        Object iActivityManagerProxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clas}, new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Log.e("HOOK",method.getName());
                if ("startActivity".equals(method.getName())) {
                    int index = -1;

                    // 获取 Intent 参数在 args 数组中的index值
                    for (int i = 0; i < args.length; i++) {
                        if (args[i] instanceof Intent) {
                            index = i;
                            break;
                        }
                    }
                    // 生成代理proxyIntent
                    Intent proxyIntent = new Intent();

                    // 设置启动注册过的ProxyActivity
                    proxyIntent.setClassName("com.yq.testmodule.hook", HookProxyActivity.class.getName());

                    // 原始Intent作为参数保存到代理Intent中
                    Intent intent = (Intent) args[index];
                    proxyIntent.putExtra(TARGET_INTENT, intent);

                    // 使用proxyIntent替换数组中的Intent
                    args[index] = proxyIntent;
                }
                return method.invoke(mInstance,args);
            }
        });

        //替换原来的IActivityManger
        mInstanceField.set(singleton,iActivityManagerProxy);
    }
}
